# 作者：要努力，努力，再努力
# 开发时间：2022/4/29 10:56


import os

filename = 'student4.txt'


def main():
    while True:
        menu()
        try:
            choice = int(input('请选择菜单：'))
        except:
            print('您输入的不是整型数据，请重新输入')
            continue
        if choice == 0:
            confirm = input('您确定要退出系统？y/n')
            if confirm == 'y':
                break
            else:
                continue
        elif choice == 1:
            insert()
        elif choice == 2:
            delete()
        elif choice == 3:
            modify()
        elif choice == 4:
            search()
        elif choice == 5:
            sort()
        elif choice == 6:
            total()
        elif choice == 7:
            show()
        else:
            print('您输入的数据不正确')
            continue


def menu():
    print('=========================学生信息管理系统=======================')
    print('----------------------------选择菜单---------------------------')
    print('\t\t\t\t\t1.录入学生信息')
    print('\t\t\t\t\t2.删除学生信息')
    print('\t\t\t\t\t3.修改学生信息')
    print('\t\t\t\t\t4.查找学生信息')
    print('\t\t\t\t\t5.排序')
    print('\t\t\t\t\t6.统计学生人数')
    print('\t\t\t\t\t7.显示所有学生信息')
    print('\t\t\t\t\t0.退出系统')


def insert():
    while True:
        student_list = []
        try:
            id = int(input('请输入学生ID：'))
        except:
            print('输入的id不是整型，请重新输入')
            continue
        name = input('请输入学生姓名：')
        try:
            english = int(input('英语成绩：'))
            python = int(input('python成绩：'))
            java = int(input('java成绩'))
        except:
            print('您录入的数据不是整型数据，请重新输入')
            continue
        student_list.append({'id': id, 'name': name, 'english': english, 'python': python, 'java': java})
        if student_list:
            save(student_list)
        answer = input('是否继续录入信息？y/n:')
        if answer == 'y':
            continue
        else:
            show()
            break


def save(list):
    if len(list):
        try:
            file = open(filename, 'a', encoding='utf-8')
        except:
            file = open(filename, 'w', encoding='utf-8')
        for item in list:
            file.write(str(item) + '\n')
        file.close()
        print('学生数据已保存')
    else:
        print('无数据')
        return


def delete():
    if os.path.exists(filename):
        while True:
            try:
                delete_id = int(input('请输入要删除的学生ID：'))
            except:
                print('您要删除的学生ID有误，请重新输入')
                continue
            student_list = []
            flag = False
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            if student_list:
                d = {}
                with open(filename, 'w', encoding='utf-8') as wfile:
                    for item in student_list:
                        d = dict(eval(item))
                        if d['id'] == delete_id:
                            flag = True
                        else:
                            wfile.write(str(d) + '\n')
            if flag:
                print('删除学生信息成功')
                show()
            else:
                print(f'没有找到学生id为{delete_id}的数据')
            answer = input('是否继续删除信息？y/n:')
            if answer == 'y':
                continue
            else:
                show()
                break

    else:
        print('无学生信息')
        return


def modify():
    if os.path.exists(filename):
        while True:
            try:
                modify_id = int(input('请输入需要修改的学生ID：'))
            except:
                print('您要修改的学生ID有误，请重新输入')
                continue
            flag = False
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            if student_list:
                with open(filename, 'w', encoding='utf-8') as wfile:
                    for item in student_list:
                        d = dict(eval(item))
                        if d['id'] == modify_id:
                            try:
                                d['name'] = input('请输入学生姓名：')
                                d['english'] = int(input('请输入英语成绩：'))
                                d['python'] = int(input('请输入python成绩：'))
                                d['java'] = int(input('请输入java成绩'))
                            except:
                                print('您输入的数据有误，请重新输入')
                                continue
                            wfile.write(str(d) + '\n')
                            flag = True
                        else:
                            wfile.write(str(d) + '\n')
                if flag:
                    print('修改学生信息成功')
                    show()
                else:
                    print(f'没有找到id为{modify_id}的学生信息')
            else:
                print('无学生信息')
                break

            answer = input('是否继续修改信息？y/n:')
            if answer == 'y':
                continue
            else:
                show()
                break

    else:
        print('无学生信息')
        return


def search():
    if os.path.exists(filename):
        while True:
            search_query = []
            try:
                select_id = int(input('请输入需要查找的学生ID：'))
            except:
                print('您要查找的学生ID有误，请重新输入')
                continue
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            if student_list:
                for item in student_list:
                    d = dict(eval(item))
                    if d['id'] == select_id:
                        search_query.append(d)
            else:
                print('无学生信息')
            if len(search_query):
                show_student(search_query)
            else:
                print(f'没有找到id为{select_id}的学生')

            answer = input('是否继续查找信息？y/n:')
            if answer == 'y':
                continue
            else:
                break
    else:
        print('无学生信息')
        return


def sort():
    if os.path.exists(filename):
        while True:
            student_new = []
            with open(filename, 'r', encoding='utf-8') as wfile:
                student_list = wfile.readlines()
            if student_list:
                for item in student_list:
                    d = dict(eval(item))
                    student_new.append(d)
            try:
                asc_or_dsc = int(input('请输入 1. 升序 2. 降序：'))
            except:
                print('您要排序的学生ID有误，请重新输入')
                continue
            if asc_or_dsc == 1:
                asc_or_dsc_bool = False
            else:
                asc_or_dsc_bool = True
            mode = int(input('请输入 1.按英语成绩排序 2.按python成绩排序 3.按java成绩排序 4.按总成绩排序'))
            if mode == 1:
                student_new.sort(key=lambda x: x['english'], reverse=asc_or_dsc_bool)
            elif mode == 2:
                student_new.sort(key=lambda x: x['python'], reverse=asc_or_dsc_bool)
            elif mode == 3:
                student_new.sort(key=lambda x: x['java'], reverse=asc_or_dsc_bool)
            elif mode == 4:
                student_new.sort(key=lambda x: int(x['english']) + int(x['python']) + int(x['java']),
                                 reverse=asc_or_dsc_bool)
            else:
                print('输入排序方式无效，请重新输入')
                continue
            show_student(student_new)
            break
    else:
        print('无学生信息')
        return


def total():
    if os.path.exists(filename):
        with open(filename,'r',encoding='utf-8') as wfile:
            student_list = wfile.readlines()
        if student_list:
            print(f'学生人数有{len(student_list)}个')
        else:
            print('无学生')
    else:
        print('无学生信息')
        return


def show():
    student_new = []
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
        if student_list:
            for item in student_list:
                d = dict(eval(item))
                student_new.append(d)
            show_student(student_new)
        else:
            print('无学生信息')
    else:
        print('无学生信息')
        return


def show_student(list):
    if len(list):
        format_title = '{:^6}\t{:^8}\t{:^8}\t{:^8}\t{:^8}\t{:^8}'
        print(format_title.format('ID', '姓名', '英语成绩', 'Python成绩', 'Java成绩', '总成绩'))
        format_data = '{:^6}\t{:^8}\t{:^8}\t{:^8}\t{:^8}\t{:^8}'
        for item in list:
            print(format_data.format(item.get('id'),
                                     item.get('name'),
                                     item.get('english'),
                                     item.get('python'),
                                     item.get('java'),
                                     int(item.get('english')) + int(item.get('python')) + int(item.get('java'))))
    else:
        print('无学生信息')


if __name__ == "__main__":
    main()
